import 'package:mall/utils/log/log_manager.dart';

/// 广播
class BroadcastUtil {
  static final Map<String, Set<WeakReference>> _observersDic = {};

  /// 注册监听
  static void register<T>(T observer) {
    final key = T.toString();
    _safeSet(key, observer!);
  }

  /// 移除监听
  static void unregister<T>(T observer) {
    final key = T.toString();
    _safeRemove(key, observer!);
  }

  /// 发送通知
  static void notify<T>(void Function(T) block) {
    final key = T.toString();
    final objectSet = _safeGetObjectSet(key);
    // 不能在这里移除,会导致移除后,不往下执行了
    objectSet?.forEach((observer) {
      if (observer.target != null && observer.target is T) {
        LogM.log('发送$key事件给${observer.target.runtimeType}');
         try {
          block(observer.target as T);
        }catch(e){
          LogM.log('请注意发送$key事件给${observer.target.runtimeType} 失败,原因:$e');
          // HUDUtil.toast('请注意发送$key事件给${observer.target.runtimeType} 失败');
        }
      }
    });
  }

  // 保存监听者
  static void _safeSet(String key, Object observer) {
    if (_observersDic.containsKey(key)) {
      _observersDic[key]!.removeWhere((ref) => ref.target == null);
      _observersDic[key]!.add(WeakReference(observer));
    } else {
      _observersDic[key] = {WeakReference(observer)};
    }
  }

  // 移除监听者
  static void _safeRemove(String key, Object observer) {
    _observersDic[key]?.removeWhere((ref) {
      if (ref.target == null) {
        return true;
      } else if (ref.target == observer) {
        LogM.log('$key事件移除了${ref.target.runtimeType}成功');
        return true;
      }
      return false;
    });
  }

  // 获取监听对象
  static Set<WeakReference>? _safeGetObjectSet(String key) {
    Set<WeakReference>? objectSet;

    objectSet = _observersDic[key];
    return objectSet;
  }
}
